class TreeVisualizer {
  static canvas = null;
  static ctx = null;
  static nodeCoordinates = new Map();
  static nodeRadius = 20;
  static levelHeight = 80;
  static font = '14px Arial';
  static highlightColor = '#ff4444';
  static normalColor = '#4CAF50';
  static currentTree = null;
  static animationQueue = [];
  static isAnimating = false;

  // 添加动画到队列
  static enqueueAnimation(callback, delay = 300) {
    this.animationQueue.push({callback, delay});
    if (!this.isAnimating) {
      this.processAnimationQueue();
    }
  }

  // 处理动画队列
  static processAnimationQueue() {
    if (this.animationQueue.length === 0) {
      this.isAnimating = false;
      return;
    }

    this.isAnimating = true;
    const {callback, delay} = this.animationQueue.shift();
    
    // 使用requestAnimationFrame确保动画同步
    const startTime = performance.now();
    
    const animate = (currentTime) => {
      const elapsed = currentTime - startTime;
      if (elapsed >= delay) {
        callback();
        setTimeout(() => {
          this.processAnimationQueue();
        }, 100); // 最小间隔100ms
      } else {
        requestAnimationFrame(animate);
      }
    };
    
    requestAnimationFrame(animate);
  }

  // 清除动画队列
  static clearAnimationQueue() {
    this.animationQueue = [];
    this.isAnimating = false;
  }

  static initialize(canvas) {
    TreeVisualizer.canvas = canvas;
    TreeVisualizer.ctx = canvas.getContext('2d');
  }

  static clearCanvas() {
    TreeVisualizer.ctx.clearRect(0, 0, TreeVisualizer.canvas.width, TreeVisualizer.canvas.height);
  }

  static drawTree(tree) {
    TreeVisualizer.currentTree = tree;
    TreeVisualizer.clearCanvas();
    if (tree && tree.root) {
      TreeVisualizer._drawNode(tree.root, TreeVisualizer.canvas.width / 2, 50, TreeVisualizer.canvas.width / 4);
    } else {
      TreeVisualizer.clearCanvas();
      TreeVisualizer.ctx.font = '20px Arial';
      TreeVisualizer.ctx.fillStyle = '#666';
      TreeVisualizer.ctx.textAlign = 'center';
      TreeVisualizer.ctx.fillText('Tree is empty', TreeVisualizer.canvas.width / 2, TreeVisualizer.canvas.height / 2);
    }
  }

  static _drawNode(node, x, y, offsetX) {
    if (node.left) {
      const leftX = x - offsetX;
      const leftY = y + TreeVisualizer.levelHeight;
      TreeVisualizer.ctx.beginPath();
      TreeVisualizer.ctx.moveTo(x, y);
      TreeVisualizer.ctx.lineTo(leftX, leftY);
      TreeVisualizer.ctx.strokeStyle = TreeVisualizer.normalColor;
      TreeVisualizer.ctx.stroke();
      TreeVisualizer._drawNode(node.left, leftX, leftY, offsetX / 2);
    }

    if (node.right) {
      const rightX = x + offsetX;
      const rightY = y + TreeVisualizer.levelHeight;
      TreeVisualizer.ctx.beginPath();
      TreeVisualizer.ctx.moveTo(x, y);
      TreeVisualizer.ctx.lineTo(rightX, rightY);
      TreeVisualizer.ctx.strokeStyle = TreeVisualizer.normalColor;
      TreeVisualizer.ctx.stroke();
      TreeVisualizer._drawNode(node.right, rightX, rightY, offsetX / 2);
    }

    TreeVisualizer.ctx.beginPath();
    TreeVisualizer.ctx.arc(x, y, TreeVisualizer.nodeRadius, 0, Math.PI * 2);
    TreeVisualizer.ctx.fillStyle = '#fff';
    TreeVisualizer.ctx.fill();
    TreeVisualizer.ctx.strokeStyle = TreeVisualizer.normalColor;
    TreeVisualizer.ctx.stroke();

    TreeVisualizer.ctx.font = TreeVisualizer.font;
    TreeVisualizer.ctx.textAlign = 'center';
    TreeVisualizer.ctx.textBaseline = 'middle';
    TreeVisualizer.ctx.fillStyle = '#000';
    TreeVisualizer.ctx.fillText(node.value, x, y);
    
    TreeVisualizer.nodeCoordinates.set(node, {x, y});
  }

  // 高亮节点
  static highlightNode(node) {
    const coords = TreeVisualizer.nodeCoordinates.get(node);
    if (!coords) return;

    // Only draw the highlight effect
    TreeVisualizer.ctx.save();
    TreeVisualizer.ctx.beginPath();
    TreeVisualizer.ctx.arc(coords.x, coords.y, TreeVisualizer.nodeRadius + 4, 0, Math.PI * 2);
    TreeVisualizer.ctx.strokeStyle = TreeVisualizer.highlightColor;
    TreeVisualizer.ctx.lineWidth = 3;
    TreeVisualizer.ctx.stroke();
    TreeVisualizer.ctx.restore();
  }

  // 处理搜索路径
  static processSearchPath(path) {
    this.clearAnimationQueue();
    
    for (let i = 0; i < path.length; i++) {
      const currentNode = path[i];
      
      // 每一步都重绘树并显示当前路径
      this.enqueueAnimation(() => {
        // 重绘完整树
        this.drawTree(this.currentTree);
        
        // 高亮当前节点
        this.highlightNode(path[i]);
        
        // 如果有下一个节点，高亮它和连接线
        if (i < path.length - 1) {
          this.highlightNode(path[i+1]);
          this.drawConnection(path[i], path[i+1], this.highlightColor);
        }
      }, (i + 1) * 250); // 每个节点间隔300ms，从300ms开始
    }
    
    // 最后一步保持高亮
    this.enqueueAnimation(() => {
      this.drawTree(this.currentTree);
      if (path.length > 0) {
        this.highlightNode(path[path.length-1]);
      }
    }, path.length * 250);
  }

  // 绘制连接线
  static drawConnection(fromNode, toNode, color) {
    const fromCoords = this.nodeCoordinates.get(fromNode);
    const toCoords = this.nodeCoordinates.get(toNode);
    if (!fromCoords || !toCoords) return;

    this.ctx.save();
    this.ctx.beginPath();
    this.ctx.moveTo(fromCoords.x, fromCoords.y);
    this.ctx.lineTo(toCoords.x, toCoords.y);
    this.ctx.strokeStyle = color;
    this.ctx.lineWidth = 3;
    this.ctx.stroke();
    this.ctx.restore();
  }
}
